package com.gestclinic.common;

import java.security.MessageDigest;
import java.sql.Timestamp;

public class Security {
	
	//Primera vez al dar de alta
    public String generateHashWithSalt(String password) throws Exception
    {
    	//Generar la sal
    	long offset = Timestamp.valueOf("2012-01-01 00:00:00").getTime();
    	long end = Timestamp.valueOf("2013-01-01 00:00:00").getTime();
    	long diff = end - offset + 1;
    	Timestamp rand = new Timestamp(offset + (long)(Math.random() * diff));
    	System.out.println("Salt : " + rand);
 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        password = password + rand;
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("generateHashWithSalt: " + sb.toString());
        
        return sb.toString();
    }

    //Cada vez que se hace login
    public String getHashWithSalt(String password, String rand) throws Exception
    {
    	//Generar la sal
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        password = password + rand;
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("getHashWithSalt: " + sb.toString());
        
        return sb.toString();
    }    

}